package org.evil.deus.rss.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ProviderHelper extends SQLiteOpenHelper {

	private static final String NAME = "news.db";
	private static final int VERSION = 1;
	
	public ProviderHelper(Context context) {
		super(context, NAME, null, VERSION);
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		createChannelsTable(db);
		createItemsTable(db);
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		dropChannelsTable(db);
		dropItemsTable(db);
		createChannelsTable(db);
		createItemsTable(db);
	}
	
	private void createChannelsTable(SQLiteDatabase db) {
		StringBuilder sb = new StringBuilder();
		sb.append("CREATE TABLE ").append(RSS.Channel.TABLE).append("(");
		sb.append(RSS.Channel._ID).append(" INTEGER PRIMARY KEY AUTOINCREMENT,");
		sb.append(RSS.Channel.URL).append(" TEXT,");
		sb.append(RSS.Channel.TITLE).append(" TEXT,");
		sb.append(RSS.Channel.LINK).append(" TEXT,");
		sb.append(RSS.Channel.IMAGE).append(" TEXT,");
		sb.append(RSS.Channel.LANGUAGE).append(" TEXT,");
		sb.append(RSS.Channel.DESCRIPTION).append(" TEXT);");
		db.execSQL(sb.toString());
	}
	
	private void createItemsTable(SQLiteDatabase db) {
		StringBuilder sb = new StringBuilder();
		sb.append("CREATE TABLE ").append(RSS.Item.TABLE).append("(");
		sb.append(RSS.Item._ID).append(" INTEGER PRIMARY KEY AUTOINCREMENT,");
		sb.append(RSS.Item.TITLE).append(" TEXT,");
		sb.append(RSS.Item.LINK).append(" TEXT,");
		sb.append(RSS.Item.CATEGORY).append(" TEXT,");
		sb.append(RSS.Item.AUTHOR).append(" TEXT,");
		sb.append(RSS.Item.DATE).append(" DATE,");
		sb.append(RSS.Item.STATE).append(" INTEGER,");
		sb.append(RSS.Item.CHANNEL).append(" TEXT,");
		sb.append(RSS.Item.DESCRIPTION).append(" TEXT);");
		db.execSQL(sb.toString());
	}
	
	private void dropChannelsTable(SQLiteDatabase db) {
		db.execSQL("DROP TABLE IF EXISTS " + RSS.Channel.TABLE);
	}
	
	private void dropItemsTable(SQLiteDatabase db) {
		db.execSQL("DROP TABLE IF EXISTS " + RSS.Item.TABLE);
	}
}
